# -*- coding: utf-8 -*-
# @Time    : 2022/11/16 15:21
# @Author  : yangyuexiong
# @Email   : yang6333yyx@126.com
# @File    : main.py
# @Software: PyCharm


from openpyxl import Workbook

from commands.app_commands.Excel.excel_base.main import ExcelHandle, insert_range_tuple


class ExcelInsertHandle(ExcelHandle):
    """插入"""

    def __init__(self, excel_path=None):
        super(ExcelInsertHandle, self).__init__(excel_path=excel_path)

        self.insert_range_dict = {
            "a_line": self.insert_a_line,
            "one_column": self.insert_one_column
        }

    def insert_a_line(self, sheet, row_num, **kwargs):
        """

        插入一行
        :param sheet: sheet对象
        :param row_num: 行号
        :param kwargs:
        :return:
        """

        print('=== insert_a_line ===')
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')

        try:
            sheet.insert_rows(int(row_num))
        except BaseException as e:
            msg = f'插入行失败: {e}'
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def insert_one_column(self, sheet, column_num, **kwargs):
        """

        插入一列
        :param sheet: sheet对象
        :param column_num: 列号
        :param kwargs:
        """

        print('=== insert_one_column ===')
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')

        # sheet.insert_cols(2)

        sheet_columns = list(sheet.columns)

        num = None
        for index, i in enumerate(sheet_columns, 1):
            coordinate = i[0].coordinate
            if coordinate == f"{column_num}1":
                # print(index)
                num = index

        if not num:
            msg = f'插入列失败: 列 {column_num} 不存在'
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        try:
            sheet.insert_cols(num)
        except BaseException as e:
            msg = f'插入列失败: {e}'
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def excel_insert(self, sheet_name=None, insert_range=None, **kwargs):
        """
        插入
        :param sheet_name: sheet名称
        :param insert_range: 范围类型
        :param kwargs: 对应范围类型的扩展参数
        :return:

        a_line:
            行号
            {
                "row_num":"1"
            }
        one_column:
            列号
            {
                "column_num":"A",
            }
        """
        try:
            if isinstance(self.wb, Workbook):
                self.wb.save(self.excel_path)
                # print(f"读取:{self.excel_path.split('/')[-1]}")

                if insert_range not in insert_range_tuple:
                    msg = f'插入范围错误:{insert_range}'
                    # print(msg)
                    self.throw['status'] = False
                    self.throw['message'] = msg
                    return self.throw

                if not self.check_sheet_name(sheet_name):
                    return self.throw

                sheet = self.get_sheet(sheet_name)
                kwargs['sheet'] = sheet
                insert_func = self.insert_range_dict.get(insert_range)
                insert_func(**kwargs)
                return self.throw

        except BaseException as e:
            # print(e)
            self.return_error_file()
            return self.throw
